#!/usr/bin/env python
import sys
import os
#在环境中添加django环境

sys.path.insert(0,'./')

if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.settings.dev'

import django
django.setup()




'''----------------以上为配置python脚本Django环境---------'''
from apps.contents.fengzhuang import get_categories
from apps.goods.utils.breadcrumb import get_breadcrumb
from apps.goods.models import SKU
from django.template import loader
from django.conf import settings

#定义批量生成静态文件的函数
def details_staticlize(sku):

    #商品分类
    contents_categories = get_categories()
    #面包屑导航
    breadcrumb = get_breadcrumb(sku.category)  #需要一个cat3
    #构建商品规格键
    skus_specs = sku.specs.order_by('spec_id')
    sku_key=[]
    for spec in skus_specs:
        sku_key.append(spec.option.id)
    skus = sku.spu.sku_set.all()
    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.specs.order_by('spec_id')
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
    goods_specs = sku.spu.specs.order_by('id')
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(goods_specs):
        return
    for index, spec in enumerate(goods_specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # 该规格的选项
        spec_options = spec.options.all()
        for option in spec_options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))
        spec.spec_options = spec_options


    #获得全部数据
    context = {
        'categories':contents_categories,
        'breadcrumb':breadcrumb,
        'sku':sku,
        'specs':goods_specs
    }

    #获得模板
    template = loader.get_template('detail.html')
    #将得到的数据渲染模板
    html_text = template.render(context)

    #写入文件
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
                             'meiduo_mall/static/details/%s.html'%sku.id)
    print(file_path)

    with open(file_path,'w',encoding='utf-8') as f:
        f.write(html_text)

if __name__ == '__main__':
    skus = SKU.objects.all()
    for sku in skus:
        details_staticlize(sku)




